<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场景ID" prop="sceneId">
        <el-input
          v-model="queryParams.sceneId"
          placeholder="请输入场景ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场景名称" prop="sceneName">
        <el-input
          v-model="queryParams.sceneName"
          placeholder="请输入场景名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场景状态" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择场景状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value === '0'"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:scene:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sceneList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场景名称" align="center" prop="sceneName" min-width="200" />
      <el-table-column label="场景状态" align="center" prop="isEnabled" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isEnabled ? 'success' : 'info'">
            {{ scope.row.isEnabled ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="匹配模式" align="center" prop="matchMode" width="120">
        <template slot-scope="scope">
          {{ scope.row.matchMode === 1 ? '任意条件' : scope.row.matchMode === 2 ? '所有条件' : '不满足' }}
        </template>
      </el-table-column>
      <el-table-column label="执行方式" align="center" prop="execType" width="120">
        <template slot-scope="scope">
          {{ scope.row.execType === 1 ? '顺序执行' : '同时执行' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:scene:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:scene:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场景配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body class="scene-dialog">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="scene-form">
            <el-form-item label="场景名称" prop="sceneName" class="is-required">
              <el-input v-model="form.sceneName" placeholder="请输入场景名称" style="width: 500px;" />
            </el-form-item>
            <el-form-item label="场景状态" prop="isEnabled">
              <el-switch
                v-model="form.isEnabled"
                :active-value="true"
                :inactive-value="false"
                active-color="#409EFF"
              />
            </el-form-item>
            <el-form-item label="备注信息" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                :rows="4"
                placeholder="请输入备注信息" 
                style="width: 500px;"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="触发器" name="trigger">
          <div class="trigger-section">
            <div class="trigger-condition">
              <span class="label">触发条件：</span>
              <el-select v-model="form.matchMode" placeholder="请选择" style="width: 150px;" @change="handleMatchModeChange">
                <el-option label="任意条件" :value="1" />
                <el-option label="所有条件" :value="2" />
                <el-option label="不满足" :value="3" />
              </el-select>
            </div>

            <div class="trigger-items">
              <div v-for="(trigger, index) in form.triggers" :key="index" class="trigger-item">
                <!-- 第一行：设备/产品选择 -->
                <div class="trigger-row">
                  <div class="trigger-content">
                    <el-select v-model="trigger.type" placeholder="设备触发" style="width: 150px;">
                      <el-option label="设备触发" value="device" />
                      <el-option label="产品触发" value="product" />
                    </el-select>
                    <div v-if="trigger.type === 'device'" class="device-count-wrapper">
                      <span class="count-label">数量</span>
                      <el-input 
                        v-model="trigger.deviceCount" 
                        placeholder="数量"
                        class="device-count"
                        readonly
                      />
                    </div>
                    <div v-if="trigger.type === 'product'" class="device-count-wrapper">
                      <span class="count-label">产品</span>
                      <el-input 
                        v-model="trigger.productName" 
                        placeholder="产品"
                        class="device-count"
                        readonly
                      />
                    </div>
                    <el-button type="primary" plain size="small" @click="handleSelectDevice(index)">
                      {{ trigger.type === 'device' ? '选择设备' : '选择产品' }}
                    </el-button>
                  </div>
                  <el-button type="danger" plain size="small" icon="el-icon-delete" @click="removeTrigger(index)">删除</el-button>
                </div>

                <!-- 第二行：触发类型选择（仅在选择了设备或产品后显示） -->
                <div v-if="showTriggerType(trigger)" class="trigger-type-row">
                  <el-select v-model="trigger.triggerType" placeholder="请选择触发类型" style="width: 150px;" @change="(val) => handleTriggerTypeChange(val, index)">
                    <el-option label="属性" value="property" />
                    <el-option label="功能" value="function" />
                    <el-option label="事件" value="event" />
                    <el-option label="设备上线" value="online" />
                    <el-option label="设备下线" value="offline" />
                  </el-select>
                  
                  <!-- 属性选择 -->
                  <el-select 
                    v-if="trigger.triggerType === 'property'"
                    v-model="trigger.modelCode" 
                    placeholder="请选择属性" 
                    style="width: 280px; margin-left: 10px;"
                    @change="(val) => handlePropertyChange(val, index)"
                  >
                    <el-option
                      v-for="item in trigger.propertyList"
                      :key="item.id"
                      :label="item.modelName"
                      :value="item.modelCode"
                    />
                  </el-select>

                  <!-- 功能选择 -->
                  <el-select 
                    v-if="trigger.triggerType === 'function'"
                    v-model="trigger.function" 
                    placeholder="请选择功能" 
                    style="width: 280px; margin-left: 10px;"
                  >
                    <el-option
                      v-for="item in trigger.functionList"
                      :key="item.id"
                      :label="item.modelName"
                      :value="item.modelCode"
                    />
                  </el-select>

                  <!-- 事件选择 -->
                  <el-select 
                    v-if="trigger.triggerType === 'event'"
                    v-model="trigger.event" 
                    placeholder="请选择事件" 
                    style="width: 280px; margin-left: 10px;"
                  >
                    <el-option
                      v-for="item in trigger.eventList"
                      :key="item.id"
                      :label="item.modelName"
                      :value="item.modelCode"
                    />
                  </el-select>
                </div>

                <!-- 第三行：运算符和数值（仅在选择了属性后显示） -->
                <div v-if="showPropertyValue(trigger)" class="trigger-value-row">
                  <el-select v-model="trigger.operator" placeholder="请选择运算符" style="width: 150px;" @change="(val) => handleOperatorChange(val, index)">
                    <el-option label="等于" value="eq" />
                    <el-option label="不等于" value="neq" />
                    <el-option label="大于" value="gt" />
                    <el-option label="大于等于" value="gte" />
                    <el-option label="小于" value="lt" />
                    <el-option label="小于等于" value="lte" />
                    <el-option label="介于" value="between" />
                  </el-select>
                  <!-- 普通输入框 -->
                  <el-input 
                    v-if="trigger.operator !== 'between'"
                    v-model="trigger.value" 
                    placeholder="请输入数值" 
                    style="width: 280px; margin-left: 10px;" 
                  />
                  <!-- 区间输入框 -->
                  <div v-else class="between-inputs" style="display: inline-flex; align-items: center; margin-left: 10px;">
                    <el-input 
                      v-model="trigger.minValue" 
                      placeholder="最小值" 
                      style="width: 135px;"
                    />
                    <span style="margin: 0 5px;">-</span>
                    <el-input 
                      v-model="trigger.maxValue" 
                      placeholder="最大值" 
                      style="width: 135px;"
                    />
                  </div>
                </div>
              </div>
            </div>

            <div class="add-btn">
              <el-button 
                type="primary" 
                plain 
                icon="el-icon-plus" 
                @click="addTrigger"
                v-if="form.matchMode !== 3 || form.triggers.length === 0">添加触发器</el-button>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="执行动作" name="action">
          <div class="action-section">
            <div class="action-config">
              <el-row>
                <el-col :span="8">
                  <div class="action-config-item">
                    <span class="label">执行方式：</span>
                    <el-select v-model="form.execType" placeholder="请选择" style="width: 150px;">
                      <el-option label="串行(顺序执行)" :value="1" />
                      <el-option label="并行(同时执行)" :value="2" />
                    </el-select>
                  </div>
                </el-col>
              </el-row>
            </div>

            <div class="action-items">
              <div v-for="(action, index) in form.actions" :key="index" class="action-item">
                <el-select v-model="action.type" placeholder="告警执行" style="width: 150px;">
                  <el-option label="告警执行" value="alarm" />
                </el-select>
                <el-button type="danger" plain size="small" icon="el-icon-delete" @click="removeAction(index)" class="delete-btn">删除</el-button>
              </div>
            </div>

            <div class="add-btn">
              <el-button type="primary" plain icon="el-icon-plus" @click="addAction">添加执行动作</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备选择对话框 -->
    <el-dialog :title="deviceDialogTitle" :visible.sync="deviceDialogVisible" width="900px" append-to-body>
      <el-form :model="deviceQueryParams" ref="deviceQueryForm" :inline="true" label-width="68px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="deviceQueryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            size="small"
            @keyup.enter.native="handleDeviceQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="deviceQueryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter.native="handleDeviceQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDeviceQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetDeviceQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="deviceLoading"
        :data="deviceList"
        @selection-change="handleDeviceSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="设备状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag v-if="dict.type.iot_device_status" :options="dict.type.iot_device_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="deviceTotal>0"
        :total="deviceTotal"
        :page.sync="deviceQueryParams.pageNum"
        :limit.sync="deviceQueryParams.pageSize"
        @pagination="getDeviceList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmDeviceSelection">确 定</el-button>
        <el-button @click="deviceDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 产品选择对话框 -->
    <el-dialog title="选择产品" :visible.sync="productDialogVisible" width="800px" append-to-body>
      <el-form :model="productQueryParams" ref="productQueryForm" :inline="true">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="productQueryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter.native="handleProductQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleProductQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table 
        v-loading="productLoading" 
        :data="productList" 
      >
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedProductId"
              :label="scope.row.id"
              @change="handleProductRadioChange(scope.row)"
              class="radio-without-label"
            />
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品类型" align="center" prop="deviceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_device_type" :value="scope.row.deviceType"/>
          </template>
        </el-table-column>
        <el-table-column label="传输协议" align="center" prop="transProtocol">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_trans_protocol" :value="scope.row.transProtocol"/>
          </template>
        </el-table-column>
        <el-table-column label="启动授权" align="center" prop="isAuthRequired">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAuthRequired"/>
          </template>
        </el-table-column>
        <el-table-column label="认证方式" align="center" prop="authMethod">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_auth_method" :value="scope.row.authMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" align="center" prop="id" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="productTotal>0"
        :total="productTotal"
        :page.sync="productQueryParams.pageNum"
        :limit.sync="productQueryParams.pageSize"
        @pagination="getProductList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmProductSelection">确 定</el-button>
        <el-button @click="productDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.scene-dialog {
  ::v-deep .el-dialog__body {
    padding: 0;
  }

  ::v-deep .el-tabs__header {
    margin: 0;
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    .el-tabs__nav-wrap {
      &::after {
        display: none;
      }
    }
  }

  ::v-deep .el-tabs__nav {
    border: none !important;
    border-radius: 4px;
    height: 32px;
    background-color: #fff;
    padding: 2px;
  }

  ::v-deep .el-tabs__item {
    height: 28px;
    line-height: 28px;
    font-size: 13px;
    padding: 0 20px;
    border: none;
    background-color: transparent;
    transition: none;
    border-radius: 4px;
    margin: 0 2px;

    &.is-active {
      background-color: #409eff;
      color: #fff;
    }

    &:not(.is-active) {
      color: #606266;
      &:hover {
        color: #409eff;
      }
    }
  }

  ::v-deep .el-tabs--card>.el-tabs__header {
    border: none;
    .el-tabs__nav {
      border: none;
    }
    .el-tabs__item {
      border: none;
    }
  }

  ::v-deep .el-tabs__active-bar {
    display: none;
  }

  ::v-deep .el-tabs__nav-prev,
  ::v-deep .el-tabs__nav-next {
    display: none;
  }
}

.scene-form {
  padding: 10px 20px;

  .el-form-item {
    margin-bottom: 22px;
  }
}

.trigger-section,
.action-section {
  padding: 10px 20px;
}

.trigger-condition,
.action-config {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;

  .label {
    color: #606266;
    margin-right: 10px;
  }

  .tip-text {
    margin-left: 15px;
    color: #909399;
    font-size: 12px;
  }
}

.trigger-items {
  margin: 10px 0;
}

.trigger-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.trigger-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  width: 100%;
}

.trigger-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.trigger-type-row,
.trigger-value-row {
  margin-top: 10px;
  margin-bottom: 10px;
  padding-right: 80px;  /* 为右侧删除按钮预留空间 */
}

.device-count-wrapper {
  display: flex;
  align-items: center;
  gap: 5px;
  margin: 0 10px;
}

.device-count {
  width: 120px;
}

.delete-btn {
  margin-left: 20px;  /* 与左侧内容保持一定距离 */
}

.add-btn {
  margin-top: 10px;
}

.action-config {
  .action-config-item {
    display: flex;
    align-items: center;

    .label {
      white-space: nowrap;
    }

    .time-input {
      width: 120px;
    }

    .unit {
      margin-left: 5px;
      color: #606266;
    }
  }
}

.add-btn {
  padding: 10px 0;
}

.dialog-footer {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
}

::v-deep .el-input-number {
  .el-input-number__decrease, 
  .el-input-number__increase {
    border: none;
    background-color: transparent;
  }
  .el-input__inner {
    text-align: left;
    padding-left: 8px;
  }
}

::v-deep .el-select .el-input__inner {
  border-color: #dcdfe6;
}

::v-deep .el-button--primary.is-plain {
  background: #ecf5ff;
}

::v-deep .el-button--danger.is-plain {
  background: #fef0f0;
}

.mb8 {
  .el-button {
    &:hover {
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
    }
  }
}

::v-deep .el-tabs__content {
  padding: 10px 0;
}

.trigger-section,
.action-section {
  .el-button--primary.is-plain {
    &:hover, &:focus {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
    }
  }

  .el-button--danger.is-plain {
    &:hover, &:focus {
      background-color: #f56c6c;
      border-color: #f56c6c;
      color: #fff;
    }
  }
}

.add-btn {
  .el-button--primary.is-plain {
    &:hover, &:focus {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
    }
  }
}

::v-deep .el-table__row {
  cursor: pointer;
  &:hover {
    background-color: #f5f7fa;
  }
  &.current-row {
    background-color: #f0f7ff;
  }
}

.el-dialog {
  ::v-deep .el-dialog__body {
    padding: 10px 20px;
  }
}

.product-search {
  padding: 10px 20px;
  margin-bottom: 10px;

  .search-item {
    display: flex;
    align-items: center;
  }
}

::v-deep .el-table {
  .el-table__row {
    cursor: pointer;
  }
  .current-row {
    background-color: #f0f7ff !important;
  }
}

.el-dialog {
  ::v-deep .el-dialog__body {
    padding: 0 0 10px 0;
  }
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #e4e7ed;
}

.radio-without-label {
  ::v-deep .el-radio__label {
    display: none;
  }
  margin-right: 0;  /* 移除右侧间距 */
}

.trigger-type-row {
  margin-top: 10px;
  margin-bottom: 10px;
}

.model-config-row {
  margin-top: 10px;
  margin-left: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
</style>

<script>
import { listScene, getScene, delScene, addScene, updateScene } from "@/api/iot/scene";
import { listDevice } from "@/api/iot/device";
import { listProduct } from "@/api/iot/product";
import { getDeviceModel, getProductModel } from "@/api/iot/model";

export default {
  name: "Scene",
  dicts: ['sys_normal_disable', 'sys_yes_no', 'iot_device_type', 'iot_trans_protocol', 'iot_auth_method', 'iot_device_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场景配置表格数据
      sceneList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sceneId: null,
        sceneName: null,
        ruleName: null,
        isEnabled: null,
        execCondition: null,
        execType: null,
        isAlarmPush: null
      },
      // 表单参数
      form: {
        id: null,
        sceneId: null,
        sceneName: null,
        isEnabled: "0",
        remark: null,
        execCondition: 1,
        execType: 1,
        silentTime: 0,
        delayTime: 0,
        triggers: [],
        actions: []
      },
      // 表单校验
      rules: {
        sceneName: [
          { required: true, message: "场景名称不能为空", trigger: "blur" }
        ],
        execCondition: [
          { required: true, message: "执行条件不能为空", trigger: "change" }
        ],
        execType: [
          { required: true, message: "执行方式不能为空", trigger: "change" }
        ]
      },
      activeName: 'basic',
      // 设备选择对话框相关数据
      deviceDialogVisible: false,
      deviceDialogTitle: '选择设备',
      deviceLoading: false,
      deviceList: [],
      deviceTotal: 0,
      selectedDevices: [],
      currentTriggerIndex: -1,
      deviceQueryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        productName: null,
        deviceId: null,
        status: null
      },
      // 产品选择对话框相关数据
      productDialogVisible: false,
      productDialogTitle: '选择产品',
      productLoading: false,
      productList: [],
      productTotal: 0,
      selectedProduct: null,
      selectedProductId: null,
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        deviceType: undefined,
        transProtocol: undefined,
        isAuthRequired: undefined,
        authMethod: undefined,
        id: undefined
      },
      // 设备状态字典
      statusOptions: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询场景配置列表 */
    getList() {
      this.loading = true;
      listScene(this.queryParams).then(response => {
        this.sceneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sceneId: null,
        sceneName: null,
        isEnabled: "0",
        remark: null,
        execCondition: 1,
        execType: 1,
        silentTime: 0,
        delayTime: 0,
        triggers: [],
        actions: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场景配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getScene(id).then(response => {
        const data = response.data;
        this.form = data;
        // 处理触发器数据
        if (this.form.triggers) {
          this.form.triggers.forEach(trigger => {
            // 设置选中的设备/产品
            if (trigger.type === 'device' && trigger.deviceCodes) {
              trigger.selectedDevices = trigger.deviceCodes.split(',').map(code => ({
                deviceCode: code,
                productId: trigger.productId,
                productName: trigger.productName
              }));
              trigger.deviceCount = trigger.selectedDevices.length;
            } else if (trigger.type === 'product' && trigger.productId) {
              trigger.selectedProduct = {
                id: trigger.productId,
                productName: trigger.productName
              };
            }
            
            // 如果有产品ID，就加载物模型数据
            if (trigger.productId) {
              getProductModel(trigger.productId).then(modelResponse => {
                if (modelResponse.code === 200) {
                  const modelList = modelResponse.rows;
                  // 设置物模型列表
                  trigger.propertyList = modelList.filter(item => item.modelType === 'property') || [];
                  trigger.functionList = modelList.filter(item => item.modelType === 'function') || [];
                  trigger.eventList = modelList.filter(item => item.modelType === 'event') || [];

                  // 根据已选择的物模型类型，设置对应的选项
                  if (trigger.triggerType === 'property' && trigger.modelCode) {
                    const selectedProperty = trigger.propertyList.find(item => item.modelCode === trigger.modelCode);
                    if (selectedProperty) {
                      trigger.modelName = selectedProperty.modelName;
                    }
                  } else if (trigger.triggerType === 'function' && trigger.function) {
                    const selectedFunction = trigger.functionList.find(item => item.modelCode === trigger.function);
                    if (selectedFunction) {
                      trigger.functionName = selectedFunction.modelName;
                    }
                  } else if (trigger.triggerType === 'event' && trigger.event) {
                    const selectedEvent = trigger.eventList.find(item => item.modelCode === trigger.event);
                    if (selectedEvent) {
                      trigger.eventName = selectedEvent.modelName;
                    }
                  }
                }
              });
            }
            
            // 处理区间值
            if (trigger.operator === 'between' && trigger.value) {
              const [minValue, maxValue] = trigger.value.split(',');
              trigger.minValue = minValue;
              trigger.maxValue = maxValue;
            }
          });
        }
        this.open = true;
        this.title = "修改场景配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            isEnabled: !!this.form.isEnabled,
            triggers: this.form.triggers.map(trigger => {
              // 处理每个触发器的设备编号和产品信息
              const processedTrigger = { ...trigger };
              if (trigger.type === 'device') {
                if (trigger.selectedDevices) {
                  // 如果重新选择了设备
                  processedTrigger.deviceCodes = trigger.selectedDevices.map(device => device.deviceCode).join(',');
                  // 补充产品信息（使用第一个设备的产品信息，因为已经确保所有设备属于同一产品）
                  if (trigger.selectedDevices.length > 0) {
                    const firstDevice = trigger.selectedDevices[0];
                    processedTrigger.productId = firstDevice.productId;
                    processedTrigger.productName = firstDevice.productName;
                  }
                } else if (trigger.deviceCodes) {
                  // 如果没有重新选择设备，保留原有的设备和产品信息
                  processedTrigger.deviceCodes = trigger.deviceCodes;
                  processedTrigger.productId = trigger.productId;
                  processedTrigger.productName = trigger.productName;
                }
              } else if (trigger.type === 'product') {
                if (trigger.selectedProduct) {
                  // 如果重新选择了产品
                  processedTrigger.productId = trigger.selectedProduct.id;
                  processedTrigger.productName = trigger.selectedProduct.productName;
                } else {
                  // 如果没有重新选择产品，保留原有的产品信息
                  processedTrigger.productId = trigger.productId;
                  processedTrigger.productName = trigger.productName;
                }
              }
              
              // 处理区间值
              if (processedTrigger.operator === 'between') {
                processedTrigger.value = `${processedTrigger.minValue},${processedTrigger.maxValue}`;
              }
              
              // 移除不需要提交的字段
              delete processedTrigger.selectedDevices;
              delete processedTrigger.selectedProduct;
              delete processedTrigger.propertyList;
              delete processedTrigger.functionList;
              delete processedTrigger.eventList;
              delete processedTrigger.minValue;
              delete processedTrigger.maxValue;
              
              return processedTrigger;
            })
          };

          console.log('Submit form:', submitData);
          if (submitData.id != null) {
            updateScene(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScene(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除场景配置编号为"' + ids + '"的数据项？').then(function() {
        return delScene(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/scene/export', {
        ...this.queryParams
      }, `scene_${new Date().getTime()}.xlsx`)
    },
    // 添加触发器
    addTrigger() {
      this.form.triggers.push({
        type: 'device',  // 默认为设备触发
        deviceCount: '',  // 设备数量
        deviceCodes: '',  // 设备编号列表（逗号分隔）
        productName: '',  // 产品名称
        productId: null,  // 产品ID
        selectedDevices: [],  // 选中的设备列表
        selectedProduct: null,  // 选中的产品
        // 以下字段在选择设备/产品后才会用到
        triggerType: '',  // 触发类型
        modelCode: '',  // 属性
        operator: '',  // 运算符
        value: '',  // 值（非区间）
        minValue: '',  // 最小值（区间）
        maxValue: '',  // 最大值（区间）
        function: '',  // 功能
        event: '',  // 事件
        propertyList: [],  // 属性列表
        functionList: [],  // 功能列表
        eventList: []  // 事件列表
      });
    },
    // 移除触发器
    removeTrigger(index) {
      this.form.triggers.splice(index, 1);
    },
    // 添加执行动作
    addAction() {
      this.form.actions.push({
        type: 'alarm'  // 默认为告警执行
      });
    },
    // 移除执行动作
    removeAction(index) {
      this.form.actions.splice(index, 1);
    },
    // 选择设备（触发器）
    handleSelectDevice(index) {
      const trigger = this.form.triggers[index];
      this.currentTriggerIndex = index;
      
      if (trigger.type === 'device') {
        this.deviceDialogVisible = true;
        this.getDeviceList();
        // 如果已有选中的设备，设置表格的选中状态
        if (trigger.selectedDevices && trigger.selectedDevices.length > 0) {
          this.$nextTick(() => {
            trigger.selectedDevices.forEach(device => {
              const row = this.deviceList.find(item => item.deviceId === device.deviceId);
              if (row) {
                this.$refs.deviceTable.toggleRowSelection(row, true);
              }
            });
          });
        }
      } else {
        this.productDialogVisible = true;
        this.getProductList();
        // 如果已有选中的产品，设置表格的选中状态
        if (trigger.selectedProduct) {
          this.$nextTick(() => {
            const row = this.productList.find(item => item.productId === trigger.selectedProduct.productId);
            if (row) {
              this.$refs.productTable.toggleRowSelection(row, true);
            }
          });
        }
      }
    },
    /** 查询设备列表 */
    getDeviceList() {
      this.deviceLoading = true;
      listDevice(this.deviceQueryParams).then(response => {
        this.deviceList = response.rows;
        this.deviceTotal = response.total;
        this.deviceLoading = false;
      });
    },
    
    /** 搜索设备按钮操作 */
    handleDeviceQuery() {
      this.deviceQueryParams.pageNum = 1;
      this.getDeviceList();
    },
    
    /** 重置设备查询操作 */
    resetDeviceQuery() {
      this.resetForm("deviceQueryForm");
      this.handleDeviceQuery();
    },
    
    /** 设备多选框选中数据 */
    handleDeviceSelectionChange(selection) {
      // 检查是否所有选中的设备都属于同一个产品
      if (selection.length > 1) {
        const firstProductId = selection[0].productId;
        const hasDifferentProduct = selection.some(device => device.productId !== firstProductId);
        
        if (hasDifferentProduct) {
          this.$modal.msgError("只能选择同一个产品下的设备");
          // 移除最后选中的设备
          const lastSelected = selection[selection.length - 1];
          this.$refs.deviceTable.toggleRowSelection(lastSelected, false);
          return;
        }
      }
      this.selectedDevices = selection;
    },
    
    /** 确认设备选择 */
    confirmDeviceSelection() {
      if (this.selectedDevices.length === 0) {
        this.$modal.msgError("请至少选择一个设备");
        return;
      }

      if (this.currentTriggerIndex >= 0) {
        const trigger = this.form.triggers[this.currentTriggerIndex];
        trigger.selectedDevices = this.selectedDevices;
        trigger.deviceCount = this.selectedDevices.length.toString();
        
        // 获取设备所属产品的物模型
        if (trigger.selectedDevices.length > 0) {
          const productId = trigger.selectedDevices[0].productId;
          getProductModel(productId).then(response => {
            if (response.code === 200) {
              const modelList = response.rows;
              console.log('Product model response:', response);
              if (modelList && modelList.length > 0) {
                trigger.propertyList = modelList.filter(item => item.modelType === 'property') || [];
                trigger.functionList = modelList.filter(item => item.modelType === 'function') || [];
                trigger.eventList = modelList.filter(item => item.modelType === 'event') || [];
                console.log('Filtered property list:', trigger.propertyList);
                console.log('Filtered function list:', trigger.functionList);
                console.log('Filtered event list:', trigger.eventList);
              }
            }
          });
        }
      }
      this.deviceDialogVisible = false;
    },

    /** 查询产品列表 */
    getProductList() {
      this.productLoading = true;
      listProduct(this.productQueryParams).then(response => {
        this.productList = response.rows;
        this.productTotal = response.total;
        this.productLoading = false;
      });
    },
    
    /** 搜索产品按钮操作 */
    handleProductQuery() {
      this.productQueryParams.pageNum = 1;
      this.getProductList();
    },
    
    /** 重置产品查询操作 */
    resetProductQuery() {
      this.resetForm("productQueryForm");
      this.handleProductQuery();
    },
    
    /** 产品radio选择事件 */
    handleProductRadioChange(row) {
      this.selectedProduct = row;
    },
    
    /** 确认产品选择 */
    confirmProductSelection() {
      if (!this.selectedProduct) {
        this.$modal.msgError("请选择一个产品");
        return;
      }
      
      if (this.currentTriggerIndex >= 0) {
        const trigger = this.form.triggers[this.currentTriggerIndex];
        trigger.selectedProduct = this.selectedProduct;
        trigger.productName = this.selectedProduct.productName;
        trigger.productId = this.selectedProduct.id;
        
        // 获取产品物模型
        getProductModel(trigger.productId).then(response => {
          if (response.code === 200) {
            const modelList = response.rows;
            console.log('Product model response:', response);
            if (modelList && modelList.length > 0) {
              trigger.propertyList = modelList.filter(item => item.modelType === 'property') || [];
              trigger.functionList = modelList.filter(item => item.modelType === 'function') || [];
              trigger.eventList = modelList.filter(item => item.modelType === 'event') || [];
              console.log('Filtered property list:', trigger.propertyList);
              console.log('Filtered function list:', trigger.functionList);
              console.log('Filtered event list:', trigger.eventList);
            }
          }
        });
      }
      this.productDialogVisible = false;
    },
    
    /** 重置产品选择 */
    resetProductSelection() {
      this.selectedProduct = null;
      this.selectedProductId = null;
    },

    /** 打开产品选择对话框时重置选择状态 */
    handleSelectProduct() {
      this.resetProductSelection();
      this.productDialogVisible = true;
      this.getProductList();
    },

    /** 处理物模型变化 */
    handleModelChange(val, index) {
      console.log('Model changed:', val, 'for index:', index);
      this.$set(this.form.modelConfigs, index, val);
    },

    /** 触发类型变化事件 */
    handleTriggerTypeChange(val, index) {
      // 重置相关字段
      const trigger = this.form.triggers[index];
      if (trigger) {
        // 重置所有相关字段
        trigger.modelCode = '';
        trigger.operator = '';
        trigger.value = '';
        trigger.function = '';
        trigger.event = '';
      }
    },

    /** 属性变化事件 */
    handlePropertyChange(val, index) {
      // 重置运算符和数值
      const trigger = this.form.triggers[index];
      if (trigger) {
        trigger.operator = '';
        trigger.value = '';
      }
    },

    /** 判断是否显示触发类型选择 */
    showTriggerType(trigger) {
      if (trigger.type === 'device') {
        return trigger.selectedDevices && trigger.selectedDevices.length > 0;
      } else if (trigger.type === 'product') {
        return trigger.selectedProduct != null;
      }
      return false;
    },

    /** 判断是否显示属性值 */
    showPropertyValue(trigger) {
      return this.showTriggerType(trigger) && trigger.triggerType === 'property' && trigger.modelCode;
    },

    /** 判断是否显示无数据提示 */
    showNoDataMessage(trigger) {
      return this.showTriggerType(trigger) && trigger.triggerType !== 'property' && trigger.triggerType !== 'function' && trigger.triggerType !== 'event';
    },

    /** 运算符变化事件 */
    handleOperatorChange(val, index) {
      const trigger = this.form.triggers[index];
      if (trigger) {
        // 重置所有值相关的字段
        trigger.value = '';
        trigger.minValue = '';
        trigger.maxValue = '';
      }
    },

    /** 处理匹配模式变化 */
    handleMatchModeChange(val) {
      if (val === 3 && this.form.triggers.length > 1) {
        this.$confirm('不满足模式下只能设置一个触发器，是否保留第一个触发器并删除其他触发器？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 只保留第一个触发器
          this.form.triggers = this.form.triggers.slice(0, 1);
          this.$message({
            type: 'success',
            message: '已保留第一个触发器'
          });
        }).catch(() => {
          // 如果用户取消，则回退到之前的匹配模式
          this.form.matchMode = this.form.matchMode === 3 ? 1 : this.form.matchMode;
        });
      }
    }
  }
};
</script> 